import React, { useState, useEffect } from 'react';
import { Modal, Form, Checkbox, DatePicker, Input, Select, Slider } from 'antd';
import moment from 'moment';
import FileUpload from '@/components/Custom/FileUpload/FileUpload';
import { ModalTypes } from './modalTypes';
import DelayedTable from './DelayedTable';
import styles from './index.less';

const { TextArea } = Input;
const { Option } = Select;

const SwitchedModal = ({ form, type, visible, setVisible, onOk, onCancel }) => {
    const { getFieldDecorator, validateFields } = form;
    const [title, setTitle] = useState('');
    const [modalStyle, setModalStyle] = useState({});
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [textArea, setTextArea] = useState('');
    const [readEndTimeMode, setReadEndTimeMode] = useState('date');
    const [nowProgress, setNowProgress] = useState(0);
    const [fileDisabled, setFileDisabled] = useState(false);

    const handleOk = () => {
        validateFields((err, values) => {
            if (err) {
                return;
            }
            setConfirmLoading(true);
            if (onOk) onOk(values);
            setTimeout(() => {
                setConfirmLoading(false);
                setVisible(false);
            }, 1000);
        });
    };

    const handleCancel = () => {
        if (onCancel) onCancel();
        setVisible(false);
    };

    const handleStartTime = value => {
        console.log(value);
    };

    const handleRealEndTime = value => {
        console.log(value);
    };

    const handleRealEndTimeChange = (date, dateString) => {
        console.log('handleRealEndTimeChange -> dateString', dateString);
        console.log('handleRealEndTimeChange -> date', date);
    };

    const handleRealEndTimePanel = (value, mode) => {
        setReadEndTimeMode(mode);
    };

    const handleTextAreaChange = e => {
        const { value } = e.target;
        setTextArea(value);
    };

    const handleFileUpload = file => {
        if (file.allFileList && file.allFileList.length >= 5) {
            setFileDisabled(true);
        } else {
            setFileDisabled(false);
        }
    };

    const handleSliderChange = value => {
        setNowProgress(value);
    };

    useEffect(() => {
        if (type) {
            setTitle(ModalTypes[type].title);
            if (ModalTypes[type] && ModalTypes[type].modalStyle) {
                setModalStyle(ModalTypes[type].modalStyle);
            } else {
                setModalStyle({});
            }
        }
    }, [type]);

    useEffect(
        () => () => {
            setTextArea('');
            setNowProgress(0);
            setFileDisabled(false);
            form.resetFields();
        },
        [visible]
    );

    const formItemLayout = {
        style: {
            paddingTop: 12,
            paddingLeft: 12,
            paddingRight: 12
        },
        labelCol: {
            span: 5
        },
        wrapperCol: {
            span: 18
        }
    };

    const renderHead = () => {
        if (type && (ModalTypes[type].content || ModalTypes[type].msg)) {
            return (
                <div className={styles.modalTitle}>
                    {ModalTypes[type].content && <div>{ModalTypes[type].content}</div>}
                    {ModalTypes[type].msg && <div className={styles.modalContent}>{ModalTypes[type].msg}</div>}
                </div>
            );
        }
        return null;
    };

    // 催办通知
    const pushItem = (label = '是否需向审核人发送催办通知') => (
        <Form.Item label={label}>
            {getFieldDecorator('pushMsg', {
                initialValue: ['1']
            })(
                <Checkbox.Group>
                    <Checkbox value="1">是</Checkbox>
                </Checkbox.Group>
            )}
        </Form.Item>
    );

    // textarea表单文本框
    const remarkItem = (remarkTitle, flag) => {
        let remarkObj = {};
        if (flag) {
            remarkObj = {
                rules: [
                    {
                        required: true,
                        message: '请输入原因！'
                    }
                ]
            };
        }
        return (
            <Form.Item label={remarkTitle}>
                {getFieldDecorator(
                    'remark',
                    remarkObj
                )(<TextArea rows={5} maxLength={500} style={{ width: 500 }} onChange={handleTextAreaChange} />)}
                <div style={{ lineHeight: 1, color: '#aaa' }}>
                    还可输入
                    <span style={{ color: 'red' }}>{500 - textArea.length < 1 ? 0 : 500 - textArea.length}</span>字
                </div>
            </Form.Item>
        );
    };

    // 添加附件
    const fileItem = (
        <Form.Item label="附件">
            <span className={styles.remarkTip}>(支持非运行文件格式，每个文件大小不超过50M，最多上传5个附件)</span>
            {getFieldDecorator('files', {
                // initialValue: {
                //     allFileList: fileList,
                //     uploadResourceFile: null
                // }
            })(
                <FileUpload
                    onChange={handleFileUpload}
                    disabled={fileDisabled}
                    checkFileSizeMsg="文件大小不能超过50MB！"
                    checkFileSize={50}
                    checkFileType="TXT,DOC,DOCX,XLS,XLSX,PPT,PPTX,PDF,EDC,SSP,DWG,EDCS,
                    BMP,JPG,PNG,TIF,GIF,PCX,TGA,EXIF,FPX,SVG,PSD,CDR,PCD,DXF,UFO,
                    EPS,AI,RAW,WMF,WEBP"
                    checkFileTypeMsg="附件格式不合规，请确认！"
                >
                    <span style={{ color: '#FFA22D', cursor: 'pointer' }}>添加附件</span>
                </FileUpload>
            )}
        </Form.Item>
    );

    // 进度
    const progressItem = (
        <Form.Item label="当前进度">
            <span
                style={{
                    position: 'absolute',
                    display: 'block',
                    width: 50,
                    left: 320,
                    color: '#585858'
                }}
            >
                {nowProgress}%
            </span>
            {getFieldDecorator('nowProgress', {
                initialValue: 0
            })(<Slider onChange={handleSliderChange} style={{ width: 300 }} />)}
        </Form.Item>
    );

    const getModalContent = () => {
        switch (type) {
            case ModalTypes.TURN_PROGRESS_1.key:
            case ModalTypes.CHILD.key:
            case ModalTypes.CANCEL_1.key:
            case ModalTypes.CHANGE.key:
            case ModalTypes.NEW.key:
                return (
                    <div>
                        <Form layout="inline">{pushItem()}</Form>
                    </div>
                );
            case ModalTypes.TURN_PROGRESS_2.key:
                return (
                    <Form {...formItemLayout} labelCol={{ span: 9 }} wrapperCol={{ span: 15 }}>
                        <Form.Item label="前置任务名称">
                            <div className={styles.taskLink}>
                                <a>
                                    【工作管理】工作管理工作管理工作管理工作管理工作管理工作管理工作管理工作管理工作管理工作管理工作管理工作管理
                                </a>
                            </div>
                        </Form.Item>
                        <Form.Item label="前置任务编号">RW061579837</Form.Item>
                        {pushItem()}
                    </Form>
                );
            case ModalTypes.TURN_PROGRESS_3.key:
                return (
                    <>
                        <Form {...formItemLayout} labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
                            <Form.Item label="实际开始时间">
                                {getFieldDecorator('startTime', {
                                    initialValue: moment(),
                                    rules: [
                                        {
                                            required: true,
                                            message: '请选择开始时间！'
                                        }
                                    ]
                                })(
                                    <DatePicker
                                        showTime
                                        style={{ width: 300 }}
                                        placeholder="请选择开始时间"
                                        format="YYYY-MM-DD HH:mm"
                                        onOk={handleStartTime}
                                    />
                                )}
                            </Form.Item>
                        </Form>
                        <DelayedTable title="逾期影响提示：当前任务已逾期，或将影响以下后置任务进度" type={type} />
                    </>
                );
            case ModalTypes.TURN_DONE_1.key:
                return <DelayedTable title="进行中子任务清单：" type={type} />;
            case ModalTypes.TURN_DONE_2.key:
            case ModalTypes.DELAY.key:
            case ModalTypes.CHILD_2.key:
            case ModalTypes.CANCEL_2.key:
            case ModalTypes.PROGRESS_2.key:
            case ModalTypes.PAUSE_2.key:
            case ModalTypes.CHANGE_2.key:
            case ModalTypes.NEW_2.key:
                return (
                    <div>
                        <Form layout="inline">{pushItem('是否需向验收人发送催办通知')}</Form>
                    </div>
                );
            case ModalTypes.TURN_DONE_3.key:
                return (
                    <>
                        <Form {...formItemLayout}>
                            <Form.Item label="温馨提示">确定后，需由验收人通过后方可生效；</Form.Item>
                            <Form.Item label="截止时间" className={styles.disabledItem}>
                                2020-05-09 17:00
                            </Form.Item>
                            <Form.Item label="实际完成时间">
                                {getFieldDecorator('realEndTime', {
                                    // initialValue: moment(),
                                    rules: [
                                        {
                                            required: true,
                                            message: '请选择实际完成时间！'
                                        }
                                    ]
                                })(
                                    <DatePicker
                                        showTime
                                        style={{ width: 300 }}
                                        placeholder="请选择实际完成时间"
                                        format={readEndTimeMode === 'date' ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm'}
                                        onOk={handleRealEndTime}
                                        onChange={handleRealEndTimeChange}
                                        onPanelChange={handleRealEndTimePanel}
                                    />
                                )}
                            </Form.Item>
                            <Form.Item label="逾期时间">0天0小时0分钟</Form.Item>
                            <Form.Item label="预估工时" className={styles.disabledItem}>
                                1天2小时0分钟
                            </Form.Item>
                            <Form.Item label="实际工时">
                                <div>
                                    {getFieldDecorator('realTimeHour', {
                                        initialValue: 0,
                                        rules: [
                                            {
                                                required: true,
                                                message: '请输入实际工时！'
                                            }
                                        ]
                                    })(<Input type="number" min={0} placeholder="请输入" style={{ width: 80 }} />)}
                                    &nbsp;&nbsp;时&nbsp;&nbsp;&nbsp;&nbsp;(0天0小时0分钟)
                                </div>
                                <div>该任务下所有子任务已耗总工时为20小时，当前输入项不可小于总工时</div>
                            </Form.Item>
                            <Form.Item label="逾期工时" className={styles.disabledItem}>
                                0天0小时0分钟
                            </Form.Item>
                            {remarkItem('备注说明')}
                            {fileItem}
                        </Form>
                        <DelayedTable
                            title="逾期影响提示：当前任务已逾期，或将影响以下后置任务进度"
                            type={type}
                            hasExpand
                        />
                    </>
                );
            case ModalTypes.RECHECK.key:
                return (
                    <Form {...formItemLayout}>
                        <Form.Item label="选择重评人员">
                            {getFieldDecorator('realEndTime', {
                                initialValue: undefined,
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择重评人员！'
                                    }
                                ]
                            })(
                                <Select showSearch style={{ width: 200 }} placeholder="请选择重评人员">
                                    <Option value="jack">Jack</Option>
                                    <Option value="lucy">Lucy</Option>
                                    <Option value="tom">Tom</Option>
                                </Select>
                            )}
                        </Form.Item>
                        {remarkItem('原因', true)}
                        {fileItem}
                    </Form>
                );
            case ModalTypes.BACK.key:
                return (
                    <Form {...formItemLayout}>
                        {remarkItem('原因', true)}
                        {fileItem}
                    </Form>
                );
            case ModalTypes.TRANSFER.key:
                return (
                    <Form {...formItemLayout}>
                        <Form.Item label="执行人">
                            {getFieldDecorator('realEndTime', {
                                initialValue: undefined,
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择执行人！'
                                    }
                                ]
                            })(
                                <Select showSearch style={{ width: 200 }} placeholder="请选择执行人">
                                    <Option value="jack">Jack</Option>
                                    <Option value="lucy">Lucy</Option>
                                    <Option value="tom">Tom</Option>
                                </Select>
                            )}
                        </Form.Item>
                        {remarkItem('原因', true)}
                        {fileItem}
                    </Form>
                );
            case ModalTypes.DELAY_2.key:
                return (
                    <Form {...formItemLayout}>
                        <Form.Item label="温馨提示">确定后，需由验收人/发起人通过后方可生效</Form.Item>
                        <Form.Item label="延期类型">
                            {getFieldDecorator('delayType', {
                                initialValue: undefined,
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择延期类型！'
                                    }
                                ]
                            })(
                                <Select showSearch style={{ width: 200 }} placeholder="请选择延期类型">
                                    <Option value="jack">任务暂停导致</Option>
                                    <Option value="lucy">预估工时不准</Option>
                                    <Option value="tom">其他优先级插入</Option>
                                    <Option value="tom1">任务变更</Option>
                                    <Option value="tom2">理解偏差</Option>
                                    <Option value="tom3">其他</Option>
                                </Select>
                            )}
                        </Form.Item>
                        <Form.Item label="原截止时间" className={styles.disabledItem}>
                            2020-05-09 17:00
                        </Form.Item>
                        <Form.Item label="申请新截止时间">
                            {getFieldDecorator('realEndTime', {
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择实际完成时间！'
                                    }
                                ]
                            })(
                                <DatePicker
                                    showTime
                                    style={{ width: 300 }}
                                    placeholder="请选择实际完成时间"
                                    format={readEndTimeMode === 'date' ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm'}
                                    onOk={handleRealEndTime}
                                    onChange={handleRealEndTimeChange}
                                    onPanelChange={handleRealEndTimePanel}
                                />
                            )}
                        </Form.Item>
                        <Form.Item label="原预估工时" className={styles.disabledItem}>
                            10小时（1天2小时0分钟）
                        </Form.Item>
                        <Form.Item label="申请新预估工时">
                            {getFieldDecorator('realTimeDay', {
                                initialValue: 0,
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入实际工时！'
                                    }
                                ]
                            })(<Input type="number" min={0} placeholder="请输入" style={{ width: 80 }} />)}
                            &nbsp;&nbsp;小时（0天0小时0分钟）
                        </Form.Item>
                        {remarkItem('原因', true)}
                        {fileItem}
                    </Form>
                );
            case ModalTypes.CANCEL_3.key:
                return <DelayedTable title="进行中子任务清单：" type={type} />;
            case ModalTypes.CANCEL_4.key:
                return (
                    <Form {...formItemLayout}>
                        <Form.Item label="温馨提示">确定后，需由验收人/发起人通过后方可生效</Form.Item>
                        <Form.Item label="是否已执行">
                            {getFieldDecorator('isExecuted', {
                                initialValue: 'yes',
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择是否已执行！'
                                    }
                                ]
                            })(
                                <Select style={{ width: 200 }} placeholder="请选择是否已执行">
                                    <Option value="yes">是</Option>
                                    <Option value="no">否</Option>
                                </Select>
                            )}
                        </Form.Item>
                        <Form.Item label="开始时间" className={styles.disabledItem}>
                            2020-05-09
                        </Form.Item>
                        <Form.Item label="实际开始时间">
                            {getFieldDecorator('realEndTime', {
                                // initialValue: moment(),
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择实际开始时间！'
                                    }
                                ]
                            })(
                                <DatePicker
                                    showTime
                                    style={{ width: 300 }}
                                    placeholder="请选择实际开始时间"
                                    format={readEndTimeMode === 'date' ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm'}
                                    onOk={handleRealEndTime}
                                    onChange={handleRealEndTimeChange}
                                    onPanelChange={handleRealEndTimePanel}
                                />
                            )}
                        </Form.Item>
                        <Form.Item label="已用工时">
                            {getFieldDecorator('usedTime', {
                                initialValue: 0,
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入已用工时！'
                                    }
                                ]
                            })(<Input type="number" min={0} placeholder="请输入" style={{ width: 80 }} />)}
                            &nbsp;&nbsp;小时（0天0小时0分钟）
                        </Form.Item>
                        {progressItem}
                        <Form.Item label="周期任务取消类型">
                            {getFieldDecorator('cancelType', {
                                initialValue: undefined,
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择取消类型！'
                                    }
                                ]
                            })(
                                <Select style={{ width: 200 }} placeholder="请选择取消类型">
                                    <Option value="yes">取消当前任务</Option>
                                    <Option value="no">取消所有任务</Option>
                                </Select>
                            )}
                        </Form.Item>
                        {remarkItem('原因', true)}
                        {fileItem}
                    </Form>
                );
            case ModalTypes.RECKON.key:
                return (
                    <Form {...formItemLayout}>
                        <Form.Item label="选择重估人员">
                            {getFieldDecorator('realEndTime', {
                                initialValue: undefined,
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择重估人员！'
                                    }
                                ]
                            })(
                                <Select showSearch style={{ width: 200 }} placeholder="请选择重估人员">
                                    <Option value="jack">Jack</Option>
                                    <Option value="lucy">Lucy</Option>
                                    <Option value="tom">Tom</Option>
                                </Select>
                            )}
                        </Form.Item>
                        {remarkItem('原因', true)}
                        {fileItem}
                    </Form>
                );
            case ModalTypes.PROGRESS.key:
                return <Form {...formItemLayout}>{progressItem}</Form>;
            // common confirm
            case ModalTypes.CONTINUE.key:
            case ModalTypes.PASS.key:
            case ModalTypes.AUDIT_2.key:
            case ModalTypes.PRESS.key:
            case ModalTypes.PRESS_2.key:
            case ModalTypes.PRESS_3.key:
                return <>{/* <div className={styles.modalTitle}>{ModalTypes[type].msg}</div> */}</>;
            case ModalTypes.PAUSE.key:
                return (
                    <Form {...formItemLayout}>
                        <Form.Item label="温馨提示">确定后，需由验收人/发起人通过后方可生效</Form.Item>
                        <Form.Item label="实际开始时间">2020-05-09</Form.Item>
                        <Form.Item label="已用工时">
                            {getFieldDecorator('usedTime', {
                                initialValue: 0,
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入已用工时！'
                                    }
                                ]
                            })(<Input type="number" min={0} placeholder="请输入" style={{ width: 80 }} />)}
                            小时（0天0小时0分钟）
                        </Form.Item>
                        {progressItem}
                        {remarkItem('原因', true)}
                        {fileItem}
                    </Form>
                );
            case ModalTypes.REFUSE.key:
                return (
                    <Form
                        {...Object.assign({}, formItemLayout, {
                            labelCol: {
                                xs: { span: 8 },
                                sm: { span: 6 }
                            }
                        })}
                    >
                        <Form.Item label="验收结果">不通过</Form.Item>
                        {remarkItem('原因', true)}
                        {fileItem}
                    </Form>
                );
            case ModalTypes.AUDIT_1.key:
                return (
                    <Form {...formItemLayout} labelCol={{ span: 6 }}>
                        <Form.Item label="上一级任务名称">
                            <div className={styles.taskLink}>
                                <a>
                                    【工作管理】工作管理工作管理工作管理工作管理工作管理工作管理工作管理工作管理工作管理工作管理工作管理工作管理
                                </a>
                            </div>
                        </Form.Item>
                        <Form.Item label="上一级任务编号">RW121798372</Form.Item>
                    </Form>
                );
            case ModalTypes.AUDIT_REFUSE.key:
                return (
                    <>
                        <Form {...formItemLayout} labelCol={{ span: 6 }}>
                            <Form.Item label="审核结果">不通过</Form.Item>
                            <Form.Item label="关联子任务处理">
                                {getFieldDecorator('childTaskResult', {
                                    initialValue: ['1']
                                })(
                                    <Checkbox.Group>
                                        <Checkbox value="1">批量审核不通过</Checkbox>
                                    </Checkbox.Group>
                                )}
                            </Form.Item>
                            {remarkItem('原因', true)}
                            {fileItem}
                        </Form>
                        <DelayedTable title="关联子任务的清单：" type={type} hasExpand />
                    </>
                );
            default:
                return '';
        }
    };

    return (
        <Modal
            title={title}
            visible={visible}
            confirmLoading={confirmLoading}
            onOk={handleOk}
            destroyOnClose
            onCancel={handleCancel}
            // footer={null}
            {...modalStyle}
            className={styles.modalWrap}
            style={{ maxHeight: '85%', overflow: 'auto', paddingBottom: 0 }}
        >
            <div className={styles.switchedModal}>
                {renderHead()}
                {getModalContent()}
            </div>
        </Modal>
    );
};

export default Form.create()(SwitchedModal);
